// pages/songDetail/songDetail.js

import request from "../../utils/request";
import Pubsub from 'pubsub-js';
import moment from "moment";

const appInstance = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false,
    song: {},
    id: '',
    currentTime: '00:00',  // 实时时间
    durationTime: '00:00', // 总时长
    musicLink: '',
    currentWidth: 0
  },

  handleSwitch(event) {
    let type = event.currentTarget.id;

    this.backgroundAudioManager.stop();

    Pubsub.subscribe("musicId", (msg, id) => {
      this.setData({ id, musicLink: '' });

      this.getSongDetail(id);

      this.playControll(true, id);

      Pubsub.unsubscribe("musicId");
    });

    Pubsub.publish("switchType", type);
  },

  handlePlay() {
    let isPlay = !this.data.isPlay;

    let { id } = this.data;
    this.playControll(isPlay, id);
  },

  async playControll(isPlay, id) {
    let musicLink = this.data.musicLink;

    if (isPlay) {
      if (!musicLink) {
        // 获取音乐播放链接
        let musicLinkData = await request('/song/url', { id });
        musicLink = musicLinkData.data[0].url;

        this.setData({
          musicLink
        })
      }

      this.backgroundAudioManager.src = musicLink;
      this.backgroundAudioManager.title = this.data.song.name;
    } else { // 暂停音乐
      this.backgroundAudioManager.pause();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { id } = options;
    this.setData({
      id
    })

    this.getSongDetail(id);

    if (appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === id) {
      this.setData({
        isPlay: true
      })
    }

    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    this.backgroundAudioManager.onPlay(() => {
      this.setData({
        isPlay: true
      });
      appInstance.globalData.isMusicPlay = true;
      appInstance.globalData.musicId = id;
    });
    this.backgroundAudioManager.onPause(() => {
      this.setData({
        isPlay: false
      });
      appInstance.globalData.isMusicPlay = false;
    });
    this.backgroundAudioManager.onStop(() => {
      this.setData({
        isPlay: false
      });
      appInstance.globalData.isMusicPlay = false;
    });
    this.backgroundAudioManager.onTimeUpdate(() => {
      let currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format('mm:ss');

      let currentWidth = this.backgroundAudioManager.currentTime / this.backgroundAudioManager.duration * 450;
      this.setData({ currentTime, currentWidth });
    });
    this.backgroundAudioManager.onEnded(() => {
      // 自动切换至下一首音乐，并且自动播放
      PubSub.publish('switchType', 'next')
      // 将实时进度条的长度还原成 0；时间还原成 0；
      this.setData({
        currentWidth: 0,
        currentTime: '00:00'
      })
    });
  },

  async getSongDetail(id) {
    let songDetail = await request('/song/detail', { ids: id });

    let durationTime = moment(songDetail.songs[0].dt).format('mm:ss');
    this.setData({
      song: songDetail.songs[0],
      durationTime
    })

    wx.setNavigationBarTitle({
      title: this.data.song.name
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})